package com.yyfax.pay.config.data.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.yyfax.commons.json.JacksonUtil;
import com.yyfax.framework.service.CacheService;
import com.yyfax.framework.service.impl.BaseServiceImpl;
import com.yyfax.pay.common.constants.CacheName;
import com.yyfax.pay.config.data.dao.PaymentRouteDao;
import com.yyfax.pay.config.data.service.PaymentRouteService;
import com.yyfax.pay.config.model.po.PaymentRoutePO;

@Service
public class PaymentRouteServiceImpl extends BaseServiceImpl implements PaymentRouteService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private PaymentRouteDao paymentRouteDao;

	public PaymentRouteServiceImpl(@Qualifier("payCacheService") CacheService cacheService) {
		super(cacheService);
	}

	@Override
	public int save(PaymentRoutePO config) throws Exception {
		if (config == null) {
			logger.error("新增商户银行支付路由信息传入参数为空返回-1");
			return -1;
		}
		clearCache(CacheName.PAYMENT_ROUTE);
		return paymentRouteDao.insert(config);
	}

	@Override
	public int modify(PaymentRoutePO config) throws Exception {
		if (config == null) {
			logger.error("修改商户银行支付路由信息传入参数为空返回-1");
			return -1;
		}
		// 更新数据清空缓存
		clearCache(CacheName.PAYMENT_ROUTE);
		return paymentRouteDao.update(config);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PaymentRoutePO> queryForList() throws Exception {
		// 从缓存读取
		List<PaymentRoutePO> pos = null;
		String json = getCache(CacheName.PAYMENT_ROUTE);
		if (StringUtils.isNotBlank(json)) {
			pos = (List<PaymentRoutePO>) JacksonUtil.fromJson(json, List.class, PaymentRoutePO.class);
			return pos;
		}
		logger.info("缓存数据为空从数据库获取查询所有商户银行支付路由信息");
		pos = paymentRouteDao.selectForList();
		if (pos != null && !pos.isEmpty()) {
			cacheService.set(CacheName.PAYMENT_ROUTE, JacksonUtil.toJson(pos));
		}
		return pos;
	}

	@SuppressWarnings("unchecked")
	@Override
	public PaymentRoutePO queryByBankCode(String merchantCode, String bankCode) throws Exception {
		if (StringUtils.isBlank(merchantCode) || StringUtils.isBlank(bankCode)) {
			logger.error("根据merchantCode，bankCode获取银行支付路由信息，有参数为空，传入merchantCode为：{}，bankCode为：{}", merchantCode, bankCode);
			return null;
		}

		String json = getCache(CacheName.PAYMENT_ROUTE);
		if (StringUtils.isNotBlank(json)) {
			List<PaymentRoutePO> list = (List<PaymentRoutePO>) JacksonUtil.fromJson(json, List.class, PaymentRoutePO.class);
			for (PaymentRoutePO po : list) {
				if (merchantCode.equals(po.getMerchantCode()) && bankCode.equals(po.getBankCode())) {
					return po;
				}
			}
		} else {
			queryForList();
		}

		logger.info("从内存获取数据为空，改为从数据库获取参数为{},{}", merchantCode, bankCode);

		return paymentRouteDao.selectByBankCode(merchantCode, bankCode);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PaymentRoutePO> queryByMerchantCode(String merchantCode) throws Exception {
		if (StringUtils.isBlank(merchantCode)) {
			logger.error("根据merchantCode获取银行支付路由信息，有参数为空，传入merchantCode为：{}", merchantCode);
			return null;
		}

		String json = getCache(CacheName.PAYMENT_ROUTE);
		if (StringUtils.isNotBlank(json)) {
			List<PaymentRoutePO> list = (List<PaymentRoutePO>) JacksonUtil.fromJson(json, List.class, PaymentRoutePO.class);
			List<PaymentRoutePO> merchantCodelist = new ArrayList<PaymentRoutePO>();
			for (PaymentRoutePO po : list) {
				if (merchantCode.equals(po.getMerchantCode())) {
					merchantCodelist.add(po);
				}
			}
			if (!merchantCodelist.isEmpty() && merchantCodelist != null) {
				return merchantCodelist;
			}
		} else {
			queryForList();
		}

		logger.info("内存中查询不到数据从数据库后去信息参数为{}", merchantCode);

		return paymentRouteDao.selectByMerchantCode(merchantCode);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<PaymentRoutePO> queryByMerchantCode(String merchantCode, String subjectType, String payMode) throws Exception {
		if (StringUtils.isBlank(merchantCode) || StringUtils.isBlank(subjectType) || StringUtils.isBlank(payMode)) {
			logger.error("根据merchantCode获取银行支付路由信息，有参数为空，传入merchantCode为：{},subject:{},payMode:{}", merchantCode, subjectType, payMode);
			return null;
		}

		String json = getCache(CacheName.PAYMENT_ROUTE);
		List<PaymentRoutePO> list = null;
		if (StringUtils.isNotBlank(json)) {
			list = (List<PaymentRoutePO>) JacksonUtil.fromJson(json, List.class, PaymentRoutePO.class);
		} else {
			logger.info("内存中查询不到数据从数据库后去信息参数为{}", merchantCode);
			list = queryForList();
		}

		if (list == null) {
			return null;
		}

		List<PaymentRoutePO> merchantCodelist = new ArrayList<PaymentRoutePO>();
		for (PaymentRoutePO po : list) {
			if (StringUtils.equals(merchantCode, po.getMerchantCode()) && StringUtils.equals(subjectType, po.getSubjectType())
					&& StringUtils.equals(payMode, po.getPayMode())) {
				merchantCodelist.add(po);
			}
		}

		if (!merchantCodelist.isEmpty() && merchantCodelist != null) {
			return merchantCodelist;
		}

		return null;
	}

	@Override
	public PaymentRoutePO queryById(int id) throws Exception {
		if (id <= 0) {
			logger.error("根据id获取银行支付路由信息,id为{},id错误返回空", id);
			return null;
		}

		return paymentRouteDao.selectById(id);
	}
}
